-- 取用户的ip
function getIp()
	local headers=ngx.req.get_headers()
	local ip=headers["X-REAL-IP"] or headers["X_FORWARDED_FOR"] or ngx.var.remote_addr or "0.0.0.0"
	return ip
end


function strSplit(str,delimiter)
    if str == nil or str == '' or delimiter == nil then
        return nil 
    end 
    local delimiter1 = delimiter
    if delimiter == '.' or delimiter == '+' or delimiter == '*' or delimiter == '-' or delimiter == '?' or delimiter == '%' then
        delimiter1 = "%"..delimiter --转义特殊字符的间隔符
    end 
    local result = {}
    for match in (str..delimiter):gmatch("(.-)"..delimiter1) do
        table.insert(result, match)
    end 
    return result
end
-- is in array return bool
function IsInTable(value, tbl)
for k,v in ipairs(tbl) do
  if v == value then
  return true;
  end
end
return false;
end

local uid = ngx.var.uid 
function uidd(uid)
local uids = ngx.shared.userIds:get("new")
if uids == nil or uids == ""
then
return false
end
if uid == "0" or uid == nil
then
return true
else
uid_array=strSplit(uids,",")
if IsInTable(uid,uid_array) then 
return true	
else
return false
end
end
end	
-- 把ip转为2进制的字符串
function ip2bit(ipstr)
local t = ""
local netn = strSplit(ipstr,'.')
for i=1,4 do
	s=tostring(byte2bin(tonumber(netn[i])))
	if t == nil or t == ""
	then
	t=s
	else
	t=t..s
	end
	print("now is :"..t)
end
return t
end

-- 把10进制转为2进制
function byte2bin(n)
local t = {}
if n == 0 or n == "0" 
then
return "00000000"
end
for i=7,0,-1 do
t[#t+1] = math.floor(n / 2^i)
n = n % 2^i
end
return table.concat(t)
end

-- 判断ip是否在网段内
function ipIsinNet(ip,netRange)

local netkey_List = ngx.shared.userRange:get_keys()
local bitip = ip2bit(ip)
	for i=1,#netkey_List
	do
	    local bitnet_str=ngx.shared.userRange:get(netkey_List[i]) --24/011111110000000000000000
		bitnet_table=strSplit(bitnet_str,"/")
		find_result=string.find(bitip,bitnet_table[2],1)
			if find_result == nil
					then
					return false
					elseif find_result==1
					then
					return true
			end
	end
end

local ip=getIp()
if ipIsinNet(ip,netRange)
then 
ngx.log(ngx.ERR,string.format("ip【%s】-> new upstream",ip))
ngx.var.target="new"
elseif uidd(uid) 
then
ngx.log(ngx.ERR,string.format("uid【%s】-> new upstream",uid))
ngx.var.target="new"
else 
ngx.log(ngx.ERR,string.format("ip【%s】/uid【%s】-> old upstream",ip,uid))
end
